import React from "react";
import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import PageHeader from "@/components/PageHeader";
import {  ControllerType } from "@/components/items-list/ItemsList";
import { BrowserRouter as Router,Link } from 'react-router-dom';//
import "./Contract.css";
import {Button, Col, Divider,Menu, Form, Input, Row, Table, ConfigProvider, Layout, Tree,Modal,Select} from "antd/lib";
import zhCN from 'antd/es/locale/zh_CN';
import ContractSuspend from "@/services/contractsuspend";
import {createBrowserHistory} from 'history'
import Enums from "@/services/enums";
import {currentUser} from "@/services/auth";
import routes from "@/services/routes";
import {WarningOutlined,SecurityScanTwoTone,DownOutlined} from "@ant-design/icons";
import notification from "@/services/notification";
import Contracts from "@/services/contracts";
import Customer from "@/services/customer";
import {get} from "lodash";
const { confirm } = Modal;
const customHistory = createBrowserHistory();
const { Sider } = Layout;
const getRowClassName = (record, index) => {
  let className = '';
  if (index % 2 === 0) className = "oddRow";
  return className
}
class PayForList extends React.Component {
  state = {
    page: 1,
    pagesize: 15,
    total:15,
    loading: false,
    code: '',
    name: '',
    contractcode: localStorage.getItem("contractcode") || '',
    contractname: localStorage.getItem("contractname") || '',
    data: [],
    gData: [],
    selectedKeys: '',
    selectedTitle: '',
    party_a: localStorage.getItem("party_a") || '',
    seltype:1,
    departmentid: localStorage.getItem("departmentid") || [],//--经办部门
    departmentdata:[],//HRP部门表
  };
  static propTypes = {
    controller: ControllerType.isRequired,
  };
    items=[{
      name:"cght",
      slug:"imgs",
      tags:"tags",
      is_draft:"df",
      is_archived:true
    }];
  componentWillMount() {
    this.loadData();
    let param={
      page: this.state.page,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      contractcode: this.state.contractcode,
      contractname: this.state.contractname,
      departmentid: this.state.departmentid,
      type: this.state.selectedKeys,
      userid: currentUser.id,
      party_a: this.state.party_a,
      seltype:this.state.seltype,
    }
    this.fetch(param);
  }
  fetch = (params = {}) => {
    this.setState({ 
      loading: true,
      seltype: params.seltype,
     });
     ContractSuspend.getlist(params).then(data => {
        this.setState({
            loading: false,
            data:data.data,
            page: params.page,
            pagesize: params.pagesize,
            total: data.total,
        });
    });
  };
  handlesel = () => {
    let param={
      page: 1,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      contractcode: this.state.contractcode,
      contractname: this.state.contractname,
      departmentid: this.state.departmentid,
      type: this.state.selectedKeys,
      userid: currentUser.id,
      party_a: this.state.party_a,
      seltype:this.state.seltype,
    }
    this.fetch(param);
  };
  tabsClick = e => {
    let param={
      page: 1,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      contractcode: this.state.contractcode,
      contractname: this.state.contractname,
      departmentid: this.state.departmentid,
      type: this.state.selectedKeys,
      userid: currentUser.id,
      party_a: this.state.party_a,
      seltype: e.key,
    }
    this.fetch(param);
  };
   handleTableChange = (pagination, filters, sorter) => {
    let field=sorter.field;
    let order=0;
    if(sorter.order==="descend"){
      order=1;
    }
    let param={
      field: field,
      order: order,
      page: pagination.current,
      pagesize: pagination.pageSize,
      code: this.state.code,
      name: this.state.name,
      contractcode: this.state.contractcode,
      contractname: this.state.contractname,
      departmentid: this.state.departmentid,
      type: this.state.selectedKeys,
      userid: currentUser.id,
      party_a: this.state.party_a,
      seltype:this.state.seltype,
    }
    this.fetch(param);
  };
  handleDelete = record => {
    if(record.status !==0)
    {
       notification.error("只有在草稿状态可以删除，删除失败！");
       return;
    }
    confirm({
      title: '确定删除合同违约赔偿结算单?',
      icon: <WarningOutlined />,
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        ContractSuspend.delete(record).then(()=>{
          notification.success("合同违约赔偿结算单删除成功.");
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            code: this.state.code,
            name: this.state.name,
            contractcode: this.state.contractcode,
            contractname: this.state.contractname,
            departmentid: this.state.departmentid,
            type: this.state.selectedKeys,
            userid: currentUser.id,
            party_a: this.state.party_a,
            seltype:this.state.seltype,
          }
          this.fetch(param);
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  loadData=()=> {
    Enums.items("contract_enum").then(data => {
      const loop = (das, index) => {
        let items=[];
        das.forEach((item) => {
          item.icon= <SecurityScanTwoTone />;
          if (item.children) {
            item.children= loop(item.children, index+1);
          }
          items.push(item);
        });
        return items;
      };
      let datas=loop(data,0);
      this.setState({
        loading: false,
        gData: datas,
        selectedKeys: '',
        selectedTitle: '',
      });
    });
    let params={
      billtype: "",
      id: 0,
    }
    Contracts.getsellist(params).then(data => {
      this.setState({
        contractsdata: data,
      });
    });
    params={
      code: "",
      name: "",
      userid: currentUser.id,
    }
    Customer.querydepartment(params).then(data => {
      this.setState({
        departmentdata: data,
      });
    });
  }
  onSelect = (selectedKeys, e) => {
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            code: this.state.code,
            name: this.state.name,
            contractcode: this.state.contractcode,
            contractname: this.state.contractname,
            departmentid: this.state.departmentid,
            type: selectedKeys[0],
            userid: currentUser.id,
            party_a: this.state.party_a,
            seltype:this.state.seltype,
          }
          this.fetch(param);
    // this.setState({
    //   selectedKeys: selectedKeys[0],
    //   selectedTitle: e.node.props.title,
    // });
};
onDragEnter = info => {
    console.log(info);
  };
  render() {
    // const { currentPage } = this.state;
      const paginationProps = {
            showSizeChanger: true,
            // showQuickJumper: true,
            total: this.state.total, // 数据总数
            pageSize: parseInt(this.state.pagesize), // 每页条数
            current: parseInt(this.state.page), // 当前页码
            pageSizeOptions: ["10", "20", "30","100"],
            showTotal: ((total) => {
              return `共 ${total} 条`;
            }),
          };
        const listcolumns = [
      {
        title: '合同编码',
        key: 'contractcode',
        dataIndex: 'contractcode',
        render: (text, record) => (
          <Router  history={customHistory}>
            <Link to={`/contract/suspend/new/${record.id}`}>{text}</Link>
           </Router>
        ),
        sorter: (a, b) => a.contractcode > b.contractcode ? 1 : -1
      },
      {
        title: '合同名称',
        dataIndex: 'contractname',
        key: 'contractname',
        sorter: (a, b) => a.contractname > b.contractname ? 1 : -1
      },
      {
        title: '合同单位',
        dataIndex: 'partyaname',
        key: 'partyaname',
        sorter: (a, b) => a.partyaname > b.partyaname ? 1 : -1
      },
      {
        title: '经办部门',
        dataIndex: 'orgname',
        key: 'orgname',
        sorter: (a, b) => a.orgname > b.orgname ? 1 : -1
      },
      {
        title: '合同金额',
        dataIndex: 'amount',
        key: 'amount',
        render: (text, record) => (
          <span>
            <label>
              {record.pricetype ===0 ? text: 0}
            </label>
          </span>
                  ),
        sorter: (a, b) => a.amount > b.amount ? 1 : -1
      },
      {
        title: '赔偿金额',
        dataIndex: 'amount',
        key: 'amount',
        render: (text, record) => (
          <span>
            <label>
              {record.pricetype ===0 ? 0: text}
            </label>
          </span>
                  ),
        sorter: (a, b) => a.amount > b.amount ? 1 : -1
      },
      {
        title: '操作',
        key: 'action',
        render: (record) => (
          <span>
            <a className="clickable">
              {record.strstatus}
            </a>
            <Divider type="vertical" />
            <a className="clickable"  onClick={() => this.handleDelete(record)}>删除</a>
          </span>
        ),
      },
    ];
    return (
  <ConfigProvider locale={zhCN}>
          <div  style={{width:"400px",height:"60px"}}>
            <div style={{width:"20px",height:"50px", float: "left"}}>
            </div>
              <div style={{width:"50px",height:"50px", float: "left"}}>
              <img src="/static/images/contractseal.png"/>
            </div>
              <div style={{width:"320px",height:"30px",float:"left"}}>
              <h3 style={{margin:"7px",padding:"0"}}>合同违约赔偿结算单列表</h3>
            </div>
          </div>
      <Layout>
        <Layout style={{ padding: '0 24px 24px' }}>
      <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
          <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同编码">
              <Input
                value={this.state.contractcode}
                onChange={e => {
                  localStorage.setItem("contractcode", e.target.value);
                  this.setState({contractcode: e.target.value});
                }}
                placeholder="合同编码"
              />
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同名称">
              <Input
                value={this.state.contractname}
                onChange={e => {
                  localStorage.setItem("contractname", e.target.value);
                  this.setState({contractname:e.target.value});}}
                placeholder="合同名称"
              />
            </Form.Item>
				  </Col>
        </Row>
        <Row>
          <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同单位">
            <Input
                value={this.state.party_a}
                onChange={e => {
                  localStorage.setItem("party_a", e.target.value);
                  this.setState({party_a:e.target.value});}}
                placeholder="合同单位"
              />
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="经办部门">
              <Select style={{ width:  400 }}
                    showSearch
                    mode="multiple"
                    allowClear
                    optionFilterProp="children"
                      value={this.state.departmentid}
                      onChange={value => {
                        localStorage.setItem("departmentid", value);
                        this.setState({departmentid:value});}} >
              {(this.state.departmentdata || []).map(item => (
                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
              ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>
          <Row>
				  <Col span={8}>
              <Button type="primary" style={{margin:"10px", width:"80px"}}>
              <Router  history={customHistory}>
              <Link to={`/contract/suspend/new/0`}>新增</Link>
             </Router>
              </Button>
          <Button type="primary" onClick={() => this.handlesel()} >
            <i className="fa fa-search m-r-5" />
            查询
          </Button>
				  </Col>
        </Row>
      </Form>
      <Menu onClick={this.tabsClick} selectedKeys={this.state.seltype} mode="horizontal">
        <Menu.Item key = "1">未结算</Menu.Item>
        <Menu.Item key = "2">已结算</Menu.Item>
      </Menu>
                 <div>
                      <Table rowKey='dazid'
                             rowClassName={(record, index) => getRowClassName(record, index)}
                             columns={listcolumns}
                             scroll={{x:'max-content'}}
                             dataSource={this.state.data}
                             pagination={paginationProps}
                             loading={this.state.loading}
                             onChange={this.handleTableChange}
                      />
                 </div>
        </Layout>
        {/* </Layout> */}
       </Layout>
  </ConfigProvider>
    );
  }
}

routes.register(
  "Contractpayfor.List",
  routeWithUserSession({
    path: "/contracts/payfor",
    title: "提交的合同违约赔偿结算单",
    render: pageProps => <PayForList {...pageProps}/>,
  })
);
routes.register(
  "Contractpayfor.List1",
  routeWithUserSession({
    path: "/contracts/payfor/approve",
    title: "待审批的合同违约赔偿结算单",
    render: pageProps => <PayForList {...pageProps}/>,
  })
);
